<template>
    <div>
        <a-calendar ref="calendar" v-model:value="day" mode="month" @select="selectDate" @panel-change="calendarChange">

            <template #dateCellRender="{ current }">
              <a-tag v-for="item in getListData(current)"
                     :color="getTagColor(item.value)">{{ item.label }}</a-tag>
            </template>

        </a-calendar>
        <a-drawer
            v-model:open="open"
            :title="day.format('YYYY-MM-DD')"
            placement="right"
        >

              <a-list item-layout="horizontal" :data-source="dataList" size="small">
                <template #renderItem="{ item,index }">
                    <a-list-item>
                        <template #extra>
                            <div class="extra">
                                <a-button type="link" danger @click="removeNode(index)">
                                    <template #icon>
                                        <CloseOutlined />
                                    </template>
                                </a-button>
                            </div>
                        </template>
                        <a-list-item-meta>
                            <template #title>
                              <a @click="updateNode(item)">{{item.title}}</a>
                            </template>
                          <template #description>
                            <p>{{item.description}}</p>
                          </template>
                            <template #avatar>
                              <a-avatar v-if="item.value<=0" style="background: green">
                                <template #icon>
                                  <ArrowDownOutlined />
                                </template>
                              </a-avatar>
                              <a-avatar v-else style="background: red">
                                <template #icon>
                                  <ArrowUpOutlined />
                                </template>
                              </a-avatar>
                            </template>
                        </a-list-item-meta>
                    </a-list-item>
                </template>

                <template #footer>
                    <div style="text-align: center;">
                        <a-button type="dashed" block @click="addNewNode">+ADD</a-button>
                    </div>
                </template>
            </a-list>



        </a-drawer>
        <add-dialog ref="addDialog" @success="refreshDrawer"/>
    </div>


</template>

<script>

import { mapState } from "vuex";
import {getCalendar,deleteCalendar} from "@/api/calendar";
import {generateCalendar} from "@/common/utils";
import {Calendar,Drawer,List,ListItem,ListItemMeta,Avatar,Tag,Modal} from "ant-design-vue";
import addDialog from "./add.vue";
import dayjs from "dayjs";
import { cloneDeep } from 'lodash';
import { ArrowDownOutlined,ArrowUpOutlined,CloseOutlined } from '@ant-design/icons-vue';


export default{
    components: {
        ArrowDownOutlined,
        ArrowUpOutlined,
        CloseOutlined,
        ACalendar:Calendar,
        ADrawer:Drawer,
        AList: List,
        AListItem: ListItem,
        AListItemMeta: ListItemMeta,
        AAvatar: Avatar,
        ATag: Tag,
        addDialog
    },
    data(){
        return {
            day: dayjs(),
            open: false,
            drawerTitle: "",
            calendarData: [],
            dataList: []
        }
    },
    computed:{
        ...mapState('app',['sectors'])
    },
    mounted(){

        this.getNode();

    },
    methods:{
      getTagColor(value){
        if (value>0){
          return "red";
        } else if (value===0){
          return "default";
        } else {
          return "green";
        }
      },
        getListData(value){
            let listData = [];

            for (let i =0;i<this.calendarData.length;i++){
                if (value.isSame(dayjs(this.calendarData[i].date),'day')){

                    let sum = 0;

                    this.calendarData[i].nodes.forEach((a,ai)=>{
                      sum += a.sector.length
                    })

                    this.calendarData[i].nodes.forEach((a,ai)=>{

                      a.sector.forEach((b)=>{
                        if (listData.length < 4){
                          listData.push({
                            value: a.value,
                            label: this.sectors.find(c=>c.code === b).name,
                          })
                        } else if(listData.length === 4){
                          listData.push({
                            value: 0,
                            label: "+" + (sum - 4),
                          })
                        }
                      })

                    })

                    break;
                }
            }



            return listData;

        },
        async getNode(date = new Date()){

            const calendar = generateCalendar(date);

            let startDate = dayjs(calendar[0].date).format("YYYY-MM-DD");
            let endDate = dayjs(calendar[calendar.length - 1].date).format("YYYY-MM-DD");

            // console.log(startDate,endDate)

            let res = await getCalendar({
                startDate,
                endDate
            })

            this.calendarData = res.data;
        },
        calendarChange(date){
            this.getNode(new Date(date))
        },
        selectDate(date,{ source }){
            if (source === 'date') {
                this.open = true;

                let calendar = this.calendarData.find(a=> dayjs(a.date).isSame(date,'day'));

                if (calendar){

                  let nodes = cloneDeep(calendar.nodes);

                  nodes.map(a=>{
                    let title = "";
                    a.sector.forEach((sector,index)=>{
                      title += this.sectors.find(a=>a.code === sector).name;
                      if (index!==a.sector.length-1){
                        title += ","
                      }
                    })
                    a.title = title;
                    return a;
                  })

                  this.dataList = nodes;
                } else {
                  this.dataList = []
                }
            }
        },
        addNewNode(){
            this.$refs['addDialog'].show(this.day)
        },
        updateNode(item){
            this.$refs['addDialog'].show(this.day,item)
        },
        refreshDrawer(date){
          this.getNode(new Date(date)).then(()=>{
            this.selectDate(dayjs(date),{source:"date"})
          });
        },
        removeNode(index){
          Modal.confirm({
            title: "确认删除",
            content: "真的要删除吗?",
            onOk:()=>{
              deleteCalendar(this.dataList[index]._id).then(()=>{
                this.getNode(new Date(this.day));
                this.dataList.splice(index,1);
              })
            }
          })

        }
    }
}

</script>

<style>

.ant-picker-calendar-mode-switch{
    display: none;
}
.ant-list-item{
    position: relative;
    .extra{
        position: absolute;
        top: 0;
        right: 0;
    }
}
.ant-list p{
  white-space: pre-line;
}

</style>
